/**
 * Copyright (C) 2017 - 2020 https://github.com/joewee
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bifrost.util;

import com.bifrost.common.util.HttpRequestUtils;
import com.bifrost.constant.CouponReleaseMode;
import com.bifrost.constant.CouponTypes;
import com.bifrost.constant.OrderStatus;
import com.bifrost.constant.OrderType;
import com.bifrost.constant.ShippingType;
import com.bifrost.entity.*;
import com.bifrost.model.*;
import com.bifrost.model.brand.BrandModel;
import com.bifrost.model.excel.SellDetailReportExcelModel;
import com.bifrost.model.coupon.WXCouponDetailVO;
import com.bifrost.model.coupon.WXCouponTotalVO;
import com.bifrost.model.order.OrderDetailVO;
import com.bifrost.model.vo.PromotionSkuVO;
import com.bifrost.model.vo.coupon.CouponDetailVO;
import com.bifrost.model.vo.report.OrderReportVO;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 类型转换工具集合
 *
 * @author joewee
 * @version 1.0.0
 * @Date 2017/11/1 14:08
 */
public class TransformUtils {

    public static ProductModel transformToProductModel(ProductSku sku) {
        return SkuTransformUtils.transformToProductModel(sku);
    }

    public static StoreModel transformToStoreModel(MerchantStore store) {
        if (null == store) {
            return null;
        }
        StoreModel model = new StoreModel();
        model.setDomainName(store.getDomainName());
        model.setExternalId(store.getExternalId());
        model.setId(store.getMerchantId());
        List<String> medias = store.getStoreMediaMaps().stream().map(StoreMediaMap::getMedia).map(Media::getUrl).collect(Collectors.toList());
        if (!medias.isEmpty()) {
            model.setMedias(medias);
        }
        Media logo = store.getMedia();
        model.setLogo(logo == null ? null : logo.getUrl());
        model.setOrderCount(store.getOrderCount());
        model.setRatesCount(store.getRatesCount());
        model.setStorePhone(store.getStorePhone());
        model.setStoreAddress(store.getStoreAddress());
        model.setStoreName(store.getStoreName());
        model.setDesc(store.getDescription());
        model.setLongitude(store.getLongitude());
        model.setLatitude(store.getLatitude());
        model.setSortOrder(store.getSortOrder() == null ? 0 : store.getSortOrder());
        model.setUpdatedTimestamp(store.getUpdatedTimestamp());
        //TODO 获取门店提供的服务及价格
        model.setServices(new ArrayList<>());
        return model;
    }

    public static CouponModel transformToCouponModel(CouponDetail detail) {
        CouponModel model = new CouponModel();
        Media media = detail.getCoupon().getMedia();
        model.setCode(String.format("%d", detail.getCouponCode()));
        model.setCustomerId(detail.getCustomer().getCustomerId());
        model.setDescription(detail.getCouponDescription());
        model.setDiscount(detail.getDiscountAmount());
        model.setDiscountType(detail.getDiscountType());
        model.setName(detail.getCouponName());
        model.setEndTime(detail.getActiveEndDate());
        model.setStartTime(detail.getActiveStartDate());
        model.setId(detail.getCouponDetailId());
        model.setCouponId(detail.getCoupon().getCouponId());
        model.setType(detail.getForOrderType());
        model.setOrderRequirement(detail.getOrderMinTotal());
        model.setValidityType(detail.getValidityType());
        model.setValidityDays(detail.getValidityDays());
        model.setConsumedTime(detail.getConsumedTime());
        model.setQuantity(1);
        model.setImgUrl(media == null ? null : HttpRequestUtils.getUrl(media.getUrl()));
        return model;
    }

    public static CouponModel transformToCouponModel(Coupon coupon) {
        CouponModel model = new CouponModel();
        Media media = coupon.getMedia();
        model.setDescription(coupon.getCouponDescription());
        model.setDiscount(coupon.getDiscountAmount());
        model.setDiscountType(coupon.getDiscountType());
        model.setName(coupon.getCouponName());
        model.setEndTime(coupon.getActiveEndDate());
        model.setStartTime(coupon.getActiveStartDate());
        model.setId(coupon.getCouponId());
        model.setType(coupon.getForOrderType());
        model.setOrderRequirement(coupon.getOrderMinTotal());
        model.setQuantity(coupon.getCouponQuantity());
        model.setQuantityAvailable(coupon.getQuantityAvailable());
        model.setBonusPoints(coupon.getBonusPoints() == null ? BigInteger.valueOf(0) : coupon.getBonusPoints());
        model.setImgUrl(media==null?null: HttpRequestUtils.getUrl(media.getUrl()));
        model.setPrice(String.valueOf(coupon.getPrice()));
        /*
         * CASH:前端展示为现金支付
         * BONUS_POINT：前端展示为积分购买
         * 如有需要，请自行添加其他条件
         */
        if(CouponReleaseMode.CASH_PURCHASE.equalsIgnoreCase(coupon.getReleaseMode())){
            model.setPayType("CASH");
        }else {
            model.setPayType("BONUS_POINT");
        }
        return model;
    }

    public static ServiceModel transformToServiceModel(ProductService productService) {
        return new ServiceModel(productService.getServiceId(), null,
                productService.getServiceName(),
                productService.getServiceDescription(),
                null,
                1,
                productService.getServicePrice());

    }

    /**
     * 转换ProductSku为ItemModel<br>
     * 注：未设置quantity、imageurl、needService
     *
     * @param sku
     * @return
     */
    public static ItemModel transformToItemModel(ProductSku sku) {
        ItemModel itemModel = new ItemModel();
        itemModel.setSkuId(sku.getSkuId());
        itemModel.setCategoryId(sku.getCategory().getCategoryId());
        itemModel.setSkuName(sku.getSkuName());
        itemModel.setRetailPrice(sku.getRetailPrice());
        itemModel.setSalePrice(sku.getSalePrice());
        return itemModel;
    }

    public static ServiceModel transformToServiceModel(ServicePrice servicePrice) {
        ProductService service = servicePrice.getProductService();
        MerchantStore store = servicePrice.getMerchantStore();
        return new ServiceModel(service.getServiceId(),
                store.getMerchantId(),
                service.getServiceName(),
                service.getServiceDescription(),
                store.getStoreName(),
                1,
                service.getServicePrice());
    }

    public static AddressModel transformToAddressModel(CustomerAddress address) {
        AddressModel model = new AddressModel();
        model.setAddressId(address.getCustomerAddressId());
        model.setReceiver(address.getLastName());
        model.setPhone(address.getPhonePrimary());

        model.setState(address.getAddressState().getId());
        model.setStateName(address.getAddressState().getName());

        model.setCity(address.getAddressCity().getId());
        model.setCityName(address.getAddressCity().getName());

        model.setDistrict(address.getAddressDistrict().getId());
        model.setDistrictName(address.getAddressDistrict().getName());
        model.setDetail(address.getAddressStreet());
        if (address.getIsDefault()) {
            model.setIsDeafult("1");
        } else {
            model.setIsDeafult("0");
        }
        return model;
    }

    public static OrderStatusHistoryModel transformToOrderStatusHistoryModel(OrderStatusHistory history) {
        OrderStatusHistoryModel model = new OrderStatusHistoryModel(history.getDateAdded(), history.getStatusComments());
        return model;
    }

    public static BrandModel transformToBrandModel(ProductBrand productBrand) {
        String brandName = productBrand.getBrandName();
        if (StringUtils.isNotEmpty(brandName)) {
            BrandModel model = new BrandModel();
            model.setBrandId(productBrand.getProductBrandId());
            model.setBrandName(brandName);
            model.setBrandNav(PinyinUtil.getPyInitial(StringUtils.left(brandName, 1)).toUpperCase());
            return model;
        }
        return null;
    }

    public static CouponDetailVO transformToCouponDetailVO(CouponDetail cd) {
        CouponDetailVO vo = new CouponDetailVO();
        BeanUtils.copyProperties(cd, vo);
        vo.setCouponCode(String.valueOf(cd.getCouponCode()));
        Customer customer = cd.getCustomer();
        if (customer != null) {
            vo.setCustomerId(customer.getCustomerId());
            vo.setCustomerName(customer.getCustomerLastname());
        }
        List<OrderCoupon> orderCouponList = cd.getOrderCoupons();
        if (CollectionUtils.isNotEmpty(orderCouponList)) {
            List<Long> orderIds = new ArrayList<>();
            for (OrderCoupon orderCoupon : orderCouponList) {
                orderIds.add(orderCoupon.getOrder().getOrderId());
            }
            vo.setOrderIds(orderIds);
        }
        return vo;
    }

    public static Map transformToSkuKeyWord(ProductSku sku) {

        HashMap<String, Object> map = new HashMap<>(5);
        map.put("skuId", sku.getSkuId());
        map.put("externalId", sku.getExternalId());
        map.put("skuName", sku.getSkuName());
        map.put("keyword", sku.getKeyword());
        map.put("updateBy", sku.getUpdatedBy());
        return map;
    }

    public static PromotionSkuVO transfromToPromoitonSkuVo(PromotionSku promotionSku) {
        PromotionSkuVO promotionSkuVO = new PromotionSkuVO();

        promotionSkuVO.setId(promotionSku.getId());
        promotionSkuVO.setSkuName(promotionSku.getProductSku().getSkuName());

        return promotionSkuVO;
    }

    public static CustomerModel transformToCustomerModel(Customer customer) {
        CustomerModel customerModel = new CustomerModel();
        customerModel.setCustomerId(customer.getCustomerId());
        customerModel.setNickname(customer.getCustomerNickname());
        return customerModel;
    }

    public static String mapToReleaseModeCN(String releaseMode) {
        String releaseModeCN ;
        if(CouponReleaseMode.EXCHANGE.equalsIgnoreCase(releaseMode)){
            releaseModeCN = "积分兑换";
        }else if(CouponReleaseMode.CASH_PURCHASE.equalsIgnoreCase(releaseMode)){
            releaseModeCN = "现金购买";
        }else {
            releaseModeCN = "未知";
        }
        return releaseModeCN;
    }

    private static String mapToCouponTypeCodeCN(String couponTypeCode) {
        String couponTypeCodeCN ;
        if(CouponTypes.OFFLINE_COUPON.getType().equalsIgnoreCase(couponTypeCode)){
            couponTypeCodeCN = "线下券";
        }else {
            couponTypeCodeCN = "未知";
        }
        return couponTypeCodeCN;
    }

    public static OrderDetailVO transformToOrderDetailVO(OrderItem orderItem) {
        Order order = orderItem.getOrder();
        OrderDetailVO orderDetailVO = new OrderDetailVO();
        orderDetailVO.setStoreMsg("["+order.getMerchantStore().getStoreCode()+"]"+order.getMerchantStore().getStoreName());
        orderDetailVO.setOrderNum(order.getOrderNumber());
        orderDetailVO.setOrderTypeCN(mapOrderTypeToChinese(order.getOrderType()));
        orderDetailVO.setOrderStatus(mapOrderStatusToChinese(order.getOrderStatus()));
        orderDetailVO.setOrderTotal(String.valueOf(order.getOrderTotal()));
        orderDetailVO.setSkuTotal(String.valueOf(orderItem.getSkuPrice().multiply(BigDecimal.valueOf(orderItem.getSkuQuantity()))));
        orderDetailVO.setShippingType(mapShippingTypeToChinese(order.getShippingType()));
        orderDetailVO.setTotalShippingFee(order.getTotalShippingFee() == null ? BigDecimal.ZERO : order.getTotalShippingFee());
        orderDetailVO.setDatePurchased(DateUtils.format(order.getDatePurchased(),DateUtils.DEFAULT_DATE_FORMAT));
        orderDetailVO.setCardNumber(order.getCustomer().getLoyaltyCard());
        orderDetailVO.setDeliveryLastName(order.getDeliveryLastName());
        orderDetailVO.setDeliveryTelephonePrimary(order.getDeliveryTelephonePrimary());
        orderDetailVO.setDeliverAddress(order.getDeliveryStreet());
        orderDetailVO.setShippingModuleCode(order.getShippingModuleCode());
        orderDetailVO.setSkuMsg(orderItem.getSkuName());
        orderDetailVO.setRemark(orderItem.getSkuUPC());
        return orderDetailVO;
    }

    public static String mapShippingTypeToChinese(String shippingType) {
        String result = "未知";
        if(ShippingType.SELF_DELIVERY.equalsIgnoreCase(shippingType)){
            result = "自提";
        }
        if(ShippingType.DELIVERY.equalsIgnoreCase(shippingType)){
            result = "快递";
        }
        if(ShippingType.BOTH.equalsIgnoreCase(shippingType)){
            result = "自提/快递";
        }
        return result;
    }

    public static String mapOrderStatusToChinese(String orderStatus) {
        String orderStatusCN = "";
        if(OrderStatus.NEW.equalsIgnoreCase(orderStatus)){
            orderStatusCN = "新建";
        }else if(OrderStatus.PURCHASED.equalsIgnoreCase(orderStatus)){
            orderStatusCN = "未支付";
        }else if(OrderStatus.PAID.equalsIgnoreCase(orderStatus)){
            orderStatusCN = "已支付";
        }else if(OrderStatus.CONFIRMED.equalsIgnoreCase(orderStatus)){
            orderStatusCN = "已确认/待发货";
        }else if(OrderStatus.SHIPPED.equalsIgnoreCase(orderStatus)){
            orderStatusCN = "已发货";
        }else if(OrderStatus.CANCELED.equalsIgnoreCase(orderStatus)){
            orderStatusCN = "取消";
        }else if(OrderStatus.FINISHED.equalsIgnoreCase(orderStatus)){
            orderStatusCN = "完成";
        }
        return orderStatusCN;
    }

    public static String mapOrderTypeToChinese(String orderType) {
        String orderTypeCN = "";
        if(OrderType.CASH_BY_COUPON.equalsIgnoreCase(orderType)){
            orderTypeCN = "现金购买优惠券订单";
        }else if(OrderType.UPKEEP.equalsIgnoreCase(orderType)){
            orderTypeCN = "保养";
        }else if(OrderType.DECORATION.equalsIgnoreCase(orderType)){
            orderTypeCN = "美容";
        }else if(OrderType.GENERAL.equalsIgnoreCase(orderType)){
            orderTypeCN = "基本";
        }else if(OrderType.GROUPON.equalsIgnoreCase(orderType)){
            orderTypeCN = "团购";
        }else if(OrderType.EXCHANGE.equalsIgnoreCase(orderType)){
            orderTypeCN = "积分兑换订单";
        }else if(OrderType.SECKILL.equalsIgnoreCase(orderType)){
            orderTypeCN = "秒杀/闪购";
        }
        return orderTypeCN;
    }

    public static List<SellDetailReportExcelModel> transformToSellDetailReportExcelModel(List<OrderReportVO> recordList) {
        List<SellDetailReportExcelModel> sellDetailReportExcelModels = Lists.newArrayList();
        if (CollectionUtils.isEmpty(recordList)) {
            throw new IllegalArgumentException("导出信息不能为空");
        }
        int totalSalesQuantity = 0;//保存总的销售数量
        double totalSalesAmount = 0;//保存总的销售额
        int index = 1;
        for (OrderReportVO orderReportVO : recordList) {
            SellDetailReportExcelModel sellDetailReportExcelModel = new SellDetailReportExcelModel();
            sellDetailReportExcelModel.setSerialNumber(String.valueOf(index++));
            //sellDetailReportExcelModel.setSellResource(orderReportVO.getSellResource());
            sellDetailReportExcelModel.setStoreMsg(orderReportVO.getStoreMsg());
            sellDetailReportExcelModel.setProductCode(orderReportVO.getProductCode());
            sellDetailReportExcelModel.setProductName(orderReportVO.getProductName());
            sellDetailReportExcelModel.setBrandName(orderReportVO.getBrandName());
            sellDetailReportExcelModel.setCategoryName(orderReportVO.getCategoryName());
            sellDetailReportExcelModel.setProductId(orderReportVO.getProductId());
            totalSalesQuantity += orderReportVO.getSalesQuantity();
            sellDetailReportExcelModel.setSalesQuantity(String.valueOf(orderReportVO.getSalesQuantity()));
            totalSalesAmount += orderReportVO.getSalesAmount();
            sellDetailReportExcelModel.setSalesAmount(String.valueOf(orderReportVO.getSalesAmount()));
            sellDetailReportExcelModels.add(sellDetailReportExcelModel);
        }
        //循环完数据计算合计
        SellDetailReportExcelModel sellDetailReportExcelModel = new SellDetailReportExcelModel();
        sellDetailReportExcelModel.setSerialNumber("合计");
        sellDetailReportExcelModel.setStoreMsg("");
        sellDetailReportExcelModel.setProductCode("");
        sellDetailReportExcelModel.setProductName("");
        sellDetailReportExcelModel.setBrandName("");
        sellDetailReportExcelModel.setCategoryName("");
        sellDetailReportExcelModel.setSalesAmount(String.valueOf(totalSalesAmount));
        sellDetailReportExcelModel.setSalesQuantity(String.valueOf(totalSalesQuantity));
        sellDetailReportExcelModels.add(sellDetailReportExcelModel);
        return sellDetailReportExcelModels;
    }
}

